package 行为型模式.备忘录模式;

import java.util.ArrayList;
import java.util.List;

/**
 * 主要组成部分
 * Originator（发起人）：需要保存状态的对象
 * Memento（备忘录）：存储Originator内部状态的对象
 * Caretaker（管理者）：负责保存和管理备忘录的对象
 */

class Memory
{
	private String state;

	Memory(String state) {
		this.state = state;
	}

	public String getState() {
		return state;
	}
}

class Creator
{
	private String state;

	Creator(String state) {
		this.state = state;
	}
	
	public void setState(String state)
	{
		this.state = state;
	}

	public String getState() {
		return state;
	}
	
	//保存
	public Memory save()
	{
		return new Memory(state);
	}
	
	//回滚
	public void rollback(String state)
	{
		this.state = state;
	}
}

class Record
{
	List<Memory> list = new ArrayList<>();
	
	//添加记录
	public void add(Memory memory)
	{
		list.add(memory);
	}
	
	public Memory get(Integer index)
	{
		return list.get(index);
	}
	
}

public class Memento 
{
	public static void main(String[] args) 
	{
		//记录
		Record record = new Record();

		Creator c = new Creator("第一次");
		record.add(	c.save());//记录片段
		System.out.println(c.getState());
		c.setState("第二次");
		record.add(	c.save());//记录片段
		System.out.println(c.getState());
		
		//回滚到第一次
		c.rollback(record.get(0).getState());
		record.add(	c.save());//记录回滚片段
		System.out.println(c.getState());

		c.setState("第三次");
		record.add(	c.save());//记录片段
		System.out.println(c.getState());

		c.rollback(record.get(1).getState());
		record.add(	c.save());//记录回滚片段
		System.out.println(c.getState());
	}
}
